import DetailHeader from '@/baseUI/detailHeader';
import Scroll from '@/baseUI/scroll';
import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
import { CSSTransition } from 'react-transition-group';
import SongsList from '../SongsList';
import { EnterLoading } from '../Singers/style';
import Loading from '@/baseUI/loading';

import { OFFSET, HEADER_HEIGHT } from '@/api/local_data';
import {
  BgLayer,
  CollectButton,
  Container,
  ImgWrapper,
  SongListWrapper,
} from './style';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { getSingerInfoAction, changeEnterLoadingAction } from './store';
import MusicNote from '@/baseUI/music-note';
export default memo(function SingerDetail(props) {
  const [showStatus, setShowStatus] = useState(true);
  const { loading, artist, songsOfArtist, playList } = useSelector(
    (state) => ({
      loading: state.singerInfo.loading,
      artist: state.singerInfo.artist,
      songsOfArtist: state.singerInfo.songsOfArtist,
      playList: state.player.playList,
    }),
    shallowEqual
  );
  const dispatch = useDispatch();
  const collectButtonRef = useRef();
  const imageWrapperRef = useRef();
  const songScrollWrapperRef = useRef();
  const songScrollRef = useRef();
  const headerRef = useRef();
  const layerRef = useRef();
  const musicNoteRef = useRef();

  const musicAnimation = (x, y) => {
    musicNoteRef.current.startAnimation({ x, y });
  };

  // 图片初始高度
  const initialHeight = useRef(0);
  const setShowStatusFalse = useCallback(() => {
    setShowStatus(false);
  }, []);
  const handleScroll = useCallback((pos) => {
    const height = initialHeight.current;
    const newY = pos.y;
    const imageDOM = imageWrapperRef.current;
    const buttonDOM = collectButtonRef.current;
    const headerDOM = headerRef.current;
    const layerDOM = layerRef.current;
    const minScrollY = -(height - OFFSET) + HEADER_HEIGHT;
    // 指的是滑动距离占图片高度的百分比
    const percent = Math.abs(newY / height);
    // 在歌手页的布局中，歌单列表其实是没有自己的背景的，layerDOM 其实是起一个遮罩的作用，
    // 给歌单内容提供白色背景 因此在处理的过程中，随着内容的滚动，遮罩也跟着移动。
    // 滑动主要分三种情况:
    // 1. 处理往下拉的情况，效果：图片放大，按钮跟着偏移
    if (newY > 0) {
      imageDOM.style['transform'] = `scale(${1 + percent})`;
      buttonDOM.style['transform'] = `translate3d(0, ${newY}px, 0)`;
      layerDOM.style.top = `${height - OFFSET + newY}px`;
    } else if (newY >= minScrollY) {
      // 往上滑动，但是遮罩还没超过 Header 部分
      layerDOM.style.top = `${height - OFFSET - Math.abs(newY)}px`;
      // 这时候保证遮罩的层叠优先级比图片高，不至于被图片挡住
      layerDOM.style.zIndex = 1;
      imageDOM.style.paddingTop = '75%';
      imageDOM.style.height = 0;
      imageDOM.style.zIndex = -1;
      // // 按钮跟着移动且渐渐变透明
      buttonDOM.style['transform'] = `translate3d(0, ${newY}px, 0)`;
      buttonDOM.style['opacity'] = `${1 - percent * 2}`;
    } else if (newY < minScrollY) {
      // 往上滑动，但是超过 Header 部分
      layerDOM.style.top = `${HEADER_HEIGHT - OFFSET}px`;
      layerDOM.style.zIndex = 1;
      // 防止溢出的歌单内容遮住 Header
      headerDOM.style.zIndex = 100;
      // 此时图片高度与 Header 一致
      imageDOM.style.height = `${HEADER_HEIGHT}px`;
      imageDOM.style.paddingTop = 0;
      imageDOM.style.zIndex = 99;
    }
  }, []);
  const id = props.match.params.id;
  useEffect(() => {
    dispatch(changeEnterLoadingAction(true));
    dispatch(getSingerInfoAction(id));
  }, [dispatch, id]);
  useEffect(() => {
    // 由于歌曲列表是相对于 Container 绝对定位且 top 为 0，因此初始化时，
    // 我们将歌曲列表的 top 设置为整个图片的高度，正好处在图片下方，不然列表就会与图片重叠。
    const h = imageWrapperRef.current.offsetHeight;
    songScrollWrapperRef.current.style.top = `${h - OFFSET}px`;
    initialHeight.current = h;
    // 把遮罩先放在下面，以裹住歌曲列表
    layerRef.current.style.top = `${h - OFFSET}px`;
    songScrollRef.current.refresh();
  }, []);
  return (
    <CSSTransition
      in={showStatus}
      timeout={300}
      classNames="fly"
      appear={true}
      unmountOnExit
      onExited={() => props.history.goBack()}
    >
      <Container play={playList.length}>
        <DetailHeader
          handleClick={setShowStatusFalse}
          title={artist.name}
          ref={headerRef}
        />
        <ImgWrapper bgUrl={artist.picUrl} ref={imageWrapperRef}>
          <div className="filter"></div>
        </ImgWrapper>
        <CollectButton ref={collectButtonRef}>
          <i className="iconfont">&#xe62d;</i>
          <span className="text">收藏</span>
        </CollectButton>
        <BgLayer ref={layerRef} />
        <SongListWrapper ref={songScrollWrapperRef}>
          <Scroll ref={songScrollRef} onScroll={handleScroll}>
            <SongsList
              songs={songsOfArtist}
              showCollect={false}
              musicAnimation={musicAnimation}
            />
          </Scroll>
        </SongListWrapper>
        {loading ? (
          <EnterLoading style={{ zIndex: 1111 }}>
            <Loading></Loading>
          </EnterLoading>
        ) : null}
        <MusicNote ref={musicNoteRef} />
      </Container>
    </CSSTransition>
  );
});
